<template>
  <div class="cont-wrapper">
    <kw-contsidebar ref="navMenu" :name="schoolName" :siderList="siderList" @handleAcitve="handleAcitveItem"></kw-contsidebar>
    <div class="block-container container">
      <div class="title">{{filter.className}}考生信息管理</div>
      <div class="filter-box">
        <el-form :inline="true">
          <el-form-item label="姓名：">
            <el-input v-model="filter.name"></el-input>
          </el-form-item>
          <el-form-item label="班级:">
            <!-- <el-input v-model="filter.className"></el-input> -->
            <el-select class="mx-select" v-model="filter.className" placeholder="请选择">
              <el-option
                v-for="item in siderList"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学籍号:">
            <el-input v-model="filter.code"></el-input>
          </el-form-item>
          <el-form-item label="准考证号:">
            <el-input v-model="filter.ticketCard"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button class="c-btn va-top" type="primary" @click="handleFilter">搜索</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="operation">
        <el-upload
          class="btn-upload upload-student"
          accept=".xls, .xlsx"
          :with-credentials="true"
          :action="GLOBAL.UPLOADSTUDENTINFOURL"
          :before-upload="beforeStudentInfoUpload"
          :on-success="handleStudentInfoSuccess">
          <el-button  type="primary" class="c-btn" :loading="uploadStudentInfoLoading">导入考生</el-button>
        </el-upload>
        <el-button type="primary" class="c-btn" @click="createStudent('new')">新增考生</el-button>
        <el-button type="primary" class="c-btn" @click="delAllStudent">全部删除</el-button>
        <el-button type="primary" class="c-btn" @click="uploadPhotosVisible = true; photosList = []">批量上传照片</el-button>
        <el-button type="primary" class="c-btn" :loading="reportDataLoading" @click="reportDialog = true">上报数据</el-button>
        <a :href='GLOBAL.COMMON+"/student/download_template"' class="download">下载模板</a>
      </div>
      <div class="table-wrapper">
        <el-table :data="tableData" border class="c-table" style="width: 100%" v-loading="loading">
          <el-table-column label="#" width="70">
            <template slot-scope="scope">
              {{ (listQuery.page - 1) * listQuery.pageSize  + scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column prop="name" label="考生姓名"></el-table-column>
          <el-table-column prop="sex" label="性别" width="70"></el-table-column>
          <el-table-column prop="schoolName" label="所在学校"></el-table-column>
          <el-table-column prop="className" label="班级" width="120"></el-table-column>
          <el-table-column prop="code" label="学籍号"></el-table-column>
          <el-table-column prop="ticketCard" label="准考证号">
            <template slot-scope="scope">
              <span v-if="scope.row.ticketCard">{{ scope.row.ticketCard }}</span>
              <span class="none" v-else>—</span>
            </template>
          </el-table-column>
          <el-table-column label="考生照片" width="100">
            <template slot-scope="scope">
              <span class="btn-txt" v-if="scope.row.photo" @click="previewPhoto(scope.row)">查看照片</span>
              <span class="none" v-else>未上传</span>
            </template>
          </el-table-column>
          <el-table-column label="是否上报" width="100">
            <template slot-scope="scope">
              <span class="btn-txt" v-if="scope.row.confirm">
                <el-tag size="mini" type="success">已上报</el-tag>
              </span>
              <span class="none" v-else>
                <el-tag size="mini" type="info">未上报</el-tag>
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
             <template slot-scope="scope">
              <el-upload
                class="i-con"
                :disabled="scope.row.confirm ? true : false"
                accept=".jpg, .jpeg"
                :action="GLOBAL.UPLOADPHOTO"
                :before-upload="beforePhotoUpload"
                :on-success="handlePhotoSuccess"
                :with-credentials="true"
                :data= "studentPhotoData">
                <i class="el-icon-upload2 i-con" :class="[scope.row.confirm ? 'disabled' : '']" @click="handleStudentPhotoData(scope.row, scope.$index)"></i>
              </el-upload>
              <i class="el-icon-edit i-con" :class="[scope.row.confirm ? 'disabled' : '']" @click="createStudent(scope.row, scope.$index)"></i>
              <i class="el-icon-delete i-con" :class="[scope.row.confirm ? 'disabled' : '']" @click="handleDeleteStudent(scope.row, scope.$index)"></i>
            </template>
          </el-table-column>
        </el-table>
        <kw-pagination v-if="tableData.length" :listQuery="listQuery" @changeCurrentPage="changeCurrentPage"></kw-pagination>
      </div>
    </div>

    <!-- 查看考生照片 -->
    <el-dialog :visible.sync="previewPhotoVisible" title="查看考生照片" custom-class="c-dialog" width="30%">
      <div class="dialog-cont">
        <div class="student-info-wrapper" v-if="studentInfo">
          <div class="student-photo">
            <img :src="studentInfo.photo">
          </div>
          <div class="student-info">
            <div class="si-item">
              <label>考生姓名：</label>
              <span>{{ studentInfo.name }}</span>
            </div>
            <div class="si-item">
              <label>性别：</label>
              <span>{{ studentInfo.sex }}</span>
            </div>
            <div class="si-item">
              <label>所在学校：</label>
              <span>{{ studentInfo.schoolName }}</span>
            </div>
            <div class="si-item">
              <label>所在班级：</label>
              <span>{{ studentInfo.className }}</span>
            </div>
            <div class="si-item">
              <label>学籍号：</label>
              <span>{{ studentInfo.code }}</span>
            </div>
            <div class="si-item">
              <label>准考证号：</label>
              <span>{{ studentInfo.ticketCard ? studentInfo.ticketCard : '-' }}</span>
            </div>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="c-btn" type="primary" @click="previewPhotoVisible = false">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 删除确认 -->
    <kw-delconfim :delVisible.sync="delDialog" @handleDelete="handleDelete"></kw-delconfim>
    <kw-delconfim :delVisible.sync="delAllDialog" delCont="您确定要删除学校的全部考生信息吗？删除之后将无法恢复。" @handleDelete="handleDeleteAll"></kw-delconfim>
    <kw-delconfim :delVisible.sync="reportDialog" title="上报数据" delCont="您确定要上传数据吗？上传之后将无法修改和删除考生信息" @handleDelete="reportStudentData"></kw-delconfim>
    <!-- 新增或保存考生信息 -->
    <el-dialog :visible.sync="createStudentVisible"
      :title="createTitle"
      custom-class="c-dialog"
      @close="resetForm"
      width="30%">
      <div class="dialog-cont">
        <el-form ref="ruleForm" :model="form" :rules="rules" class="c-form student-form" label-width="80px">
          <el-form-item label="考生姓名" prop="name">
            <el-input v-model="form.name"></el-input>
          </el-form-item>
          <el-form-item label="性别" prop="sex">
            <el-radio-group v-model="form.sex">
              <el-radio label="男"></el-radio>
              <el-radio label="女"></el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="所在学校">
            <el-input v-model="schoolName" disabled></el-input>
          </el-form-item>
          <el-form-item label="班级" prop="className">
            <el-select v-model="form.className" placeholder="请选择">
              <el-option
                v-for="item in siderList"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="学籍号" prop="code">
            <el-input v-model="form.code"></el-input>
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="c-btn" type="primary" @click="saveStudent">确 定</el-button>
        <el-button class="c-btn" @click="resetForm">取 消</el-button>
      </span>
    </el-dialog>
    <!-- 批量上传考生照片 -->
    <el-dialog :visible.sync="uploadPhotosVisible" title="批量上传考生照片" custom-class="c-dialog" width="30%">
      <div class="dialog-cont">
        <div class="photos-wrapper">
          <div class="">
            <el-button type="primary" class="c-btn btn-upload-photos">
              选择文件
              <input type="file" accept="image/png, image/jpeg, image/jpg" id="imgFiles" multiple name="image" ref="selectFile" class="img-files" @change="changePhotos()">
            </el-button>
            <!-- <el-input class="filepath-ipt" v-model="filePath" disabled></el-input> -->
          </div>
          <div class="photos-tip">以下为要导入的照片文件，照片文件命名格式必须为：学生姓名_学生学籍号。</div>
          <div class="files-wrap">
            <ul class="file-list wst">
              <li v-for="(item, idx) in photosList" :class="[{'active': photoActive === idx}]" :key="idx" @click="previewPhotos(idx)">{{ item.name }}</li>
            </ul>
            <div class="file-preview">
              <div class="preview-photos" :style="{backgroundImage: 'url('+imgDataUrl+')'}"></div>
              <p class="preview-tip">图片预览</p>
            </div>
          </div>
          <div class="tip-title">
            照片要求：<span @click="photosTipShow = !photosTipShow">{{ photosTipShow ? '收起' : '展开' }}</span>
          </div>
          <el-collapse-transition>
            <div class="tips" v-show="photosTipShow">
              <p>(1) 像素要求为宽295像素，高413像素（一寸证件照）。</p>
              <p>(2) 照片文件的类型为.jpg,文件大小不能大于100k。</p>
              <p>(3) 照片为近期蓝底或红底免冠正面照，不得佩戴饰物。</p>
            </div>
          </el-collapse-transition>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button class="c-btn" type="primary" :disabled="photosList.length == 0 ? true: false" :loading="uploadingPhotos"  @click="uploadPhotos">开始导入</el-button>
        <el-button class="c-btn" @click="uploadPhotosVisible = false">关闭退出</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import kwContsidebar from '@/components/ContSidebar.vue'
import kwDelconfim from '@/components/DelConfim.vue'
import kwPagination from '@/components/Pagination.vue'
export default {
  name: 'studentInfo',
  components: {
    kwContsidebar,
    kwDelconfim,
    kwPagination
  },
  data () {
    return {
      siderList: [],
      // activeIdx: 0,
      filter: {
        name: null,
        className: null,
        code: null,
        ticketCard: null
      },
      tableData: [],
      // 上传外带参数
      studentPhotoData: {
        id: null
      },
      // 预览图片
      previewPhotoVisible: false,
      photoUrl: null,
      uploadStudentInfoLoading: false,
      rowIdx: null,
      delDialog: false,
      studentId: null,
      schoolName: null,
      reportDataLoading: false,
      createStudentVisible: false,
      createTitle: '新增考生',
      form: {
        name: '',
        sex: '男',
        schoolName: '',
        className: '',
        code: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入考生姓名', trigger: 'blur' }
        ],
        sex: [
          { required: true, message: '请选择性别', trigger: 'change' }
        ],
        className: [
          { required: true, message: '请选择班级', trigger: 'change' }
        ],
        code: [
          { required: true, message: '请输入学籍号', trigger: 'blur' }
        ]
      },
      listQuery: {
        page: 1,
        pageSize: 10,
        total: null,
        totalPages: null
      },
      studentInfo: null,
      loading: false,
      uploadPhotosVisible: false,
      photosTipShow: true,
      photosList: [],
      // filePath: null,
      photoActive: null,
      imgDataUrl: null,
      uploadingPhotos: false,
      delAllDialog: false,
      reportDialog: false
    }
  },
  created () {
    this.schoolName = sessionStorage.getItem('schoolName')
    this.getClassList()
  },
  methods: {
    // 获取班级列表
    getClassList () {
      let that = this
      // sessionStorage.getItem('schoolName')
      that.$http.getClassList({ schoolName: that.schoolName }).then(res => {
        if (res.code === 20000) {
          that.siderList = res.data
          that.$refs.navMenu.getPointList(that.siderList)
          if (!this.filter.className) {
            this.filter.className = res.data[0]
            this.$refs['navMenu'].changeActive(0)
          }
          this.getStudentInfoList()
        } else {
          that.$message.error(res.msg)
        }
      })
    },
    // 选择班级
    handleAcitveItem (activeItem) {
      this.filter.className = activeItem
      this.getStudentInfoList()
    },
    // 上传图片外带参数
    handleStudentPhotoData (row, idx) {
      if (!row.confirm) {
        this.rowIdx = idx
        this.studentPhotoData.id = row.id
      }
    },
    // 预览图片
    previewPhoto (student) {
      this.studentInfo = student
      this.previewPhotoVisible = true
    },
    // 导入学生前校验
    beforeStudentInfoUpload (file) {
      const isXLSX = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel'.indexOf(file.type) >= 0
      const isLt10M = file.size / 1024 / 1024 < 10

      if (!isXLSX) {
        this.$message.error('上传文件只能是 excel 格式!')
      }
      if (!isLt10M) {
        this.$message.error('上传文件大小不能超过 10MB!')
      }
      if (isXLSX && isLt10M) {
        this.uploadStudentInfoLoading = true
        return true
      } else {
        return false
      }
    },
    // 导入学生成功回调
    handleStudentInfoSuccess (res, file) {
      if (res.code === 20000) {
        this.$message.success('导入学生信息成功')
        this.listQuery.page = 1
        this.getClassList()
      } else {
        this.$message.error(res.msg)
      }
      this.uploadStudentInfoLoading = false
    },
    // 上传照片前校验
    beforePhotoUpload (file) {
      const isJPG = file.type === 'image/jpeg'
      const isLt100K = file.size / 1024 < 100

      if (!isJPG) {
        this.$message.error('上传照片只能是 JPG 格式!')
      }
      if (!isLt100K) {
        this.$message.error('上传照片大小不能超过 100KB!')
      }
      return isJPG && isLt100K
    },
    // 上传照片成功回调
    handlePhotoSuccess (res, file) {
      if (res.code === 20000) {
        this.$message.success('上传照片成功')
        let _item = this.tableData[this.rowIdx]
        _item.photo = res.data.photo
        this.$set(this.tableData, this.rowIdx, _item)
      } else {
        this.$message.error(res.msg)
      }
    },
    // 获取学生信息列表
    getStudentInfoList () {
      let that = this
      that.loading = true
      let qsData = {
        className: that.filter.className,
        code: that.filter.code,
        name: that.filter.name,
        page: that.listQuery.page,
        pageSize: that.listQuery.pageSize,
        schoolName: that.schoolName,
        ticketCard: that.filter.ticketCard
      }
      that.$http.getStudentInfoList(qsData).then(res => {
        if (res.code === 20000) {
          that.tableData = res.data.content
          that.listQuery.total = res.data.totalElements
          that.listQuery.totalPages = res.data.totalPages
        } else {
          that.$message.error(res.msg)
        }
        that.loading = false
      })
    },
    // 删除指定考生信息
    handleDeleteStudent (row, idx) {
      if (!row.confirm) {
        this.rowIdx = idx
        this.studentId = row.id
        this.delDialog = true
      }
    },
    // 删除全部考生信息
    delAllStudent () {
      this.rowIdx = null
      this.studentId = null
      this.delAllDialog = true
    },
    // 删除回调 单个
    handleDelete () {
      let that = this
      that.$http.delStudentOne({ id: that.studentId }).then(res => {
        if (res.code === 20000) {
          that.tableData.splice(that.rowIdx, 1)
          that.$message.success('删除学生成功')
        } else {
          that.$message.error(res.msg)
        }
      })
    },
    // 删除回调 全部
    handleDeleteAll () {
      let that = this
      that.$http.delStudentAll({ schoolName: that.schoolName }).then(res => {
        if (res.code === 20000) {
          that.getClassList()
          that.$message.success('删除全部成功')
        } else {
          that.$message.error(res.msg)
        }
      })
    },
    // 校级管理员上报考生数据
    reportStudentData () {
      let that = this
      that.reportDataLoading = true
      that.$http.reportingStudentData({ schoolName: that.schoolName }).then(res => {
        that.reportDataLoading = false
        if (res.code === 20000) {
          that.$message.success('上传数据成功')
        } else {
          that.$message.error(res.msg)
        }
      })
    },
    //  添加考生弹框
    createStudent (sInfo, idx) {
      if (sInfo.confirm) {
        return false
      }
      if (sInfo === 'new') {
        this.studentId = null
        this.createTitle = '新增考生'
        this.form = {
          name: null,
          sex: '男',
          schoolName: null,
          className: null,
          code: null
        }
      } else {
        this.studentId = sInfo.id
        this.rowIdx = idx
        this.createTitle = '编辑考生'
        this.form = {
          name: sInfo.name,
          sex: sInfo.sex,
          schoolName: sInfo.schoolName,
          className: sInfo.className,
          code: sInfo.code
        }
      }
      this.createStudentVisible = true
    },
    // 添加or编辑考生
    saveStudent () {
      let that = this
      that.$refs['ruleForm'].validate((valid) => {
        if (valid) {
          that.form.schoolName = that.schoolName
          if (that.studentId) {
            that.form.id = that.studentId
          }
          that.$http.saveOrUpdateStudent(that.form).then(res => {
            if (res.code === 20000) {
              if (that.studentId) {
                let _item = that.tableData[that.rowIdx]
                _item.name = res.data.name
                _item.sex = res.data.sex
                _item.className = res.data.className
                _item.code = res.data.code
                that.$set(that.tableData, that.rowIdx, _item)
              } else {
                that.listQuery.page = 1
                that.getStudentInfoList()
              }
              that.createStudentVisible = false
            } else {
              that.$message.error(res.msg)
            }
          })
        } else {
          that.$message.error('请填写完整信息再提交')
          return false
        }
      })
    },
    // 关闭添加or编辑考生弹框
    resetForm () {
      this.$refs['ruleForm'].resetFields()
      this.createStudentVisible = false
    },
    // 搜索学生信息
    handleFilter () {
      this.listQuery.page = 1
      let _idx = ''
      this.siderList.map((item, idx) => {
        if (item === this.filter.className) {
          _idx = idx
        }
      })
      this.$refs['navMenu'].changeActive(_idx)
      this.getStudentInfoList()
    },
    // 翻页
    changeCurrentPage (queryData) {
      this.listQuery.page = queryData.page
      this.listQuery.pageSize = queryData.pageSize
      this.getStudentInfoList()
    },
    // 选择本地图片
    changePhotos () {
      this.photosList = document.querySelector('#imgFiles').files
    },
    // 本地预览图片
    previewPhotos (idx) {
      this.photoActive = idx
      let file = this.photosList[idx]
      this.imgDataUrl = this.getObjectURL(file)
    },
    // 获取本地图片的url
    getObjectURL (file) {
      let url = null
      if (window.createObjectURL !== undefined) { // basic
        url = window.createObjectURL(file)
      } else if (window.URL !== undefined) { // webkit or chrome
        url = window.URL.createObjectURL(file)
      } else if (window.URL !== undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file)
      }
      return url
    },
    // 批量上传图片
    uploadPhotos () {
      let that = this
      that.uploadingPhotos = true
      let formData = new FormData()
      for (let i = 0; i < that.photosList.length; i++) {
        formData.append('file', that.photosList[i])
      }
      formData.append('schoolName', that.schoolName)
      that.$http.uploadPhotos(formData).then(res => {
        that.uploadingPhotos = false
        debugger
        if (res.code === 20000) {
          if (res.data.unMatchPicture.length > 0 || res.data.errorPicture.length > 0 || res.data.wrongFormatPicture > 0) {
            let names = ''
            let title = ''
            if (res.data.unMatchPicture.length) {
              res.data.unMatchPicture.map(item => {
                names += item + ', '
              })
              title = '未匹配成功'
            } else if (res.data.errorPicture.length) {
              res.data.errorPicture.map(item => {
                names += item + ', '
              })
              title = '图片匹配失败'
            } else if (res.data.wrongFormatPicture.length) {
              res.data.errorPicture.map(item => {
                names += item + ', '
              })
              title = '图片格式错误'
            }
            that.$notify.error({
              title: '批量上传照片错误',
              message: names + title,
              duration: 0
            })
          } else {
            that.$message.success('图片上传成功')
            this.getClassList()
          }
        } else {
          that.$message.error(res.msg)
        }
        that.uploadPhotosVisible = false
        this.$refs.selectFile.value = ''
      })
    }
  }
}
</script>

<style lang="scss">
.upload-student{
  .el-upload-list{
    display: none !important;
  }
}
.btn-upload-photos{
  position: relative;
  span{
    color: #fff !important;
  }
}
.student-form{
  .el-radio-group{
    line-height: 34px;
  }
  .el-select{
    width: 100%;
    vertical-align: top;
  }
}
.filepath-ipt{
  display: inline-block;
  width: 180px;
  margin-left: 20px;
  .el-input__inner{
    height: 32px;
    line-height: 32px;
  }
}
</style>
<style lang="scss" scoped>
.photos-wrapper{
  .img-files{
    opacity: 0;
    position: absolute;
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    z-index: 999;
  }
  .photos-tip{
    font-size:12px;
    font-weight:400;
    color:rgba(255,65,65,1);
    margin: 10px 0;
  }
  .files-wrap{
    position: relative;
    margin-bottom: 15px;
  }
  .file-list{
    width:265px;
    height:198px;
    border:1px solid rgba(204,204,204,1);
    overflow-y: auto;
    border-radius:4px;
    li{
      padding: 5px 10px;
      cursor: pointer;
      &.active{
        background-color: #DAE4FD;
      }
    }
  }
  .file-preview{
    position: absolute;
    right: 0;
    top:0;
    .preview-photos{
      width: 130px;
      height: 174px;
      border-radius:4px;
      border:1px solid rgba(204,204,204,1);
      background-position: center;
      background-size: cover;
      background-repeat: no-repeat;
    }
    .preview-tip{
      text-align: center;
      font-size:13px;
    }
  }
  .tip-title{
    font-size:12px;
    font-weight:bold;
    color:rgba(85,85,85,1);
    span{
      font-weight: 400;
      cursor: pointer;
      &:hover{
        color: #4177FF;
      }
    }
  }
  .tips{
    font-size:12px;
    color:rgba(85,85,85,1);
    p{
      margin: 0;
    }
  }
}
.download {
  display: inline-block;
  margin-left:10px;
  padding: 2px 4px;
  background: #4177ff;
  color: #fff;
  text-decoration: none;
}
</style>
